package com.ayf.payment.game.api.service.impl;

import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import com.ayf.payment.game.api.cache.redis.RedisCacheUtil;
import com.ayf.payment.game.api.channel.ChannelHandleFactory;
import com.ayf.payment.game.api.channel.ayb.handler.AybUserTransferHandler;
import com.ayf.payment.game.api.channel.ayb.request.AybUserTransferOrderCreateReq;
import com.ayf.payment.game.api.channel.ayb.request.AybUserTransferOrderQueryReq;
import com.ayf.payment.game.api.channel.ayb.response.AybUserTransferOrderQueryRes;
import com.ayf.payment.game.api.channel.ehb.util.RSA;
import com.ayf.payment.game.api.channel.youka.util.YouKaSignUtil;
import com.ayf.payment.game.api.dto.GamePlayerCashOrderDTO;
import com.ayf.payment.game.api.dto.MerchantAccountOptions;
import com.ayf.payment.game.api.dto.MerchantDTO;
import com.ayf.payment.game.api.dto.MerchantPayOrderDTO;
import com.ayf.payment.game.api.dto.PageInfoDTO;
import com.ayf.payment.game.api.dto.alipay.AliOrderStatus;
import com.ayf.payment.game.api.dto.criteria.MerchantPayOrderCriteria;
import com.ayf.payment.game.api.dto.criteria.OrderInfoCriteria;
import com.ayf.payment.game.api.dto.platform.SettleConfigDTO;
import com.ayf.payment.game.api.dto.platform.SubstitutePayConfigDTO;
import com.ayf.payment.game.api.dto.platform.criteria.SubstitutePayCriteria;
import com.ayf.payment.game.api.entity.MerchantAccount;
import com.ayf.payment.game.api.entity.MerchantBatchPayFile;
import com.ayf.payment.game.api.entity.MerchantBatchPayFileFailReason;
import com.ayf.payment.game.api.entity.MerchantPayOrder;
import com.ayf.payment.game.api.entity.ayb.aybUserTransferBind;
import com.ayf.payment.game.api.excel.CheckUploadPayOrderDTO;
import com.ayf.payment.game.api.excel.UploadPayOrderData;
import com.ayf.payment.game.api.exception.ParameterException;
import com.ayf.payment.game.api.mapper.MerchantBatchAndPayMapper;
import com.ayf.payment.game.api.mapper.MerchantBatchPayFileFailReasonMapper;
import com.ayf.payment.game.api.mapper.MerchantPayOrderMapper;
import com.ayf.payment.game.api.service.ChannelService;
import com.ayf.payment.game.api.service.GamePlayerCashOrderService;
import com.ayf.payment.game.api.service.MerchantAccountService;
import com.ayf.payment.game.api.service.MerchantBatchPayFileService;
import com.ayf.payment.game.api.service.MerchantPayOrderService;
import com.ayf.payment.game.api.service.ayb.AybUserTransferBindService;
import com.ayf.payment.game.api.service.payment.faka.util.FaKaSignUtil;
import com.ayf.payment.game.api.service.payment.huandong.util.HuanDongSignUtil;
import com.ayf.payment.game.api.service.payment.huyu.util.HuYuSignUtil;
import com.ayf.payment.game.api.service.payment.qcjh.util.QCJHSignUtil;
import com.ayf.payment.game.api.service.payment.wanw.util.WanWSignUtil;
import com.ayf.payment.game.api.service.platform.SettleConfigService;
import com.ayf.payment.game.api.service.platform.SubstitutePayConfigService;
import com.ayf.payment.game.api.type.MerchantPayOrderStatusEnum;
import com.ayf.payment.game.api.type.YesNoFlagEnum;
import com.ayf.payment.game.api.utils.CheckUtils;
import com.ayf.payment.game.api.utils.CommonResult;
import com.ayf.payment.game.api.utils.DateUtils;
import com.ayf.payment.game.api.utils.MerchantSettleServiceChargeUtil;
import com.ayf.payment.game.api.utils.SensitiveDataUtil;
import com.ayf.payment.game.api.utils.SnowFlakeUtils;
import com.ayf.payment.game.api.utils.ValidateUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.swwx.charm.commons.lang.utils.BeanConvertUtils;
import com.swwx.charm.commons.lang.utils.LogPortal;
import com.swwx.charm.zookeeper.exception.GetLockFailedException;
import com.swwx.charm.zookeeper.exception.ReleaseLockFailedException;
import com.swwx.charm.zookeeper.lock.DistributedLock;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = Throwable.class)
@Slf4j
public class MerchantPayOrderServiceImpl implements MerchantPayOrderService {

	@Resource
	private MerchantPayOrderMapper merchantPayOrderMapper;

	@Autowired
	SubstitutePayConfigService substitutePayConfigService;

	@Autowired
	ChannelService channelService;

	@Autowired
	MerchantAccountService merchantAccountService;

	@Autowired
	SettleConfigService settleConfigService;

	@Autowired
	protected DistributedLock distributedLock;

	@Autowired
	private RedisCacheUtil redisCacheUtil;

	@Autowired
	private ChannelHandleFactory channelHandleFactory;

	@Autowired
	private AybUserTransferHandler aybUserTransferHandler;

	@Autowired
	private MerchantBatchPayFileService merchantBatchPayFileService;

	@Resource
	private MerchantBatchAndPayMapper merchantBatchAndPayMapper;

	@Resource
	private MerchantBatchPayFileFailReasonMapper merchantBatchPayFileFailReasonMapper;

	@Autowired
	private GamePlayerCashOrderService gamePlayerCashOrderService;

	@Resource
	private AybUserTransferBindService aybUserTransferBindService;


	@Override
	public CommonResult createPayOrder(MerchantDTO merchantDTO, MerchantPayOrderDTO payOrderDTO) {
		if (2 == payOrderDTO.getPayType()) {
			return createUserTransferPayOrder(merchantDTO, payOrderDTO);
		}

		CommonResult commonResult = new CommonResult();
		commonResult.setCode(200);
		commonResult.setMsg("代付受理成功");
		String traceId = SnowFlakeUtils.getTraceId();

		MerchantAccount merchantAccount = merchantAccountService.selectOne(payOrderDTO.getMerchantId());
		BigDecimal cashWithdrawal = merchantAccount.getCashWithdrawal();
		// 可提现金额
		cashWithdrawal = cashWithdrawal == null ? BigDecimal.ZERO : cashWithdrawal;
		// 代付手续费
		SettleConfigDTO settleConfigDTO = settleConfigService.getSettleConfig();
		if (settleConfigDTO.getMinPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMinPayAmount()) < 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额不能小于" + settleConfigDTO.getMinPayAmount() + "，错误码:" + traceId);
			return commonResult;
		}
		if (settleConfigDTO.getMaxPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMaxPayAmount()) > 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额不能大于" + settleConfigDTO.getMaxPayAmount() + "，错误码:" + traceId);
			return commonResult;
		}
		BigDecimal fee = MerchantSettleServiceChargeUtil.getServiceCharge(payOrderDTO.getMerchantId(), payOrderDTO.getAmount(), settleConfigDTO.getPayFeeCustom());
		if (cashWithdrawal.compareTo(payOrderDTO.getAmount()) < 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额[" + payOrderDTO.getAmount() + "]大于可提现金额[" + cashWithdrawal + "]，错误码:" + traceId);
			return commonResult;
		}
		if (payOrderDTO.getAmount().compareTo(fee) <= 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额[" + payOrderDTO.getAmount() + "]必须大于手续费金额[" + fee + "]，错误码:" + traceId);
			return commonResult;
		}
		BigDecimal totalTradeAmt = payOrderDTO.getAmount();
		Date currentDate = DateUtils.getNowDate();
		String concat = DateUtils.dateToString(DateUtils.getNowDate(), DateUtils.formatPattern_full_03).concat(SnowFlakeUtils.getUniqueId());
		String merchantOrderNo = "MF".concat(concat);
		String accountNo = payOrderDTO.getAccountNo();
		payOrderDTO.setMerchantOrderNo(merchantOrderNo);
		payOrderDTO.setQueryFlag(Integer.valueOf(0)); //默认不开启查询
		payOrderDTO.setApplyDateIndex(DateUtils.dateToInteger(currentDate));
		payOrderDTO.setCreateTime(currentDate);
		payOrderDTO.setLastUpdateTime(currentDate);
		payOrderDTO.setApplyTime(currentDate);
		payOrderDTO.setStatus(MerchantPayOrderStatusEnum.WAIT_PAY.getStatus());

		// 查询代付通道接口
		SubstitutePayConfigDTO substitutePayConfigDTO = null;
		BigDecimal amount = totalTradeAmt.subtract(fee);

		SubstitutePayCriteria substitutePayCriteria = new SubstitutePayCriteria();
		substitutePayCriteria.setChannelType(payOrderDTO.getPayType());
		substitutePayCriteria.setChannelStatus(1);
		List<SubstitutePayConfigDTO> list = substitutePayConfigService.getListSubstitutePayConfigByChannelCode(substitutePayCriteria);
		String failMsg = "";
		if (!CollectionUtils.isEmpty(list)) {
			String finalStatus = "YH_ERROR";
			JSONObject balanceParam = new JSONObject();
			// 商户系统内部订单号，要求64个字符内，只能是数字、大小写字母_-|* 且在同一个商户号下唯一
			balanceParam.put("traceId", traceId);
			balanceParam.put("bankName", payOrderDTO.getBankName());
			for (SubstitutePayConfigDTO dto : list) {
				balanceParam.put("substitutePayConfigId", dto.getId());
				JSONObject balanceQuery = channelHandleFactory.getHandler(dto.getChannelCode()).balanceQuery(balanceParam);
				Integer status = balanceQuery.getInteger("status");
				if (status == 1) {
					finalStatus = "YE_ERROR";
					BigDecimal balance = balanceQuery.getBigDecimal("balance");
					if (balance.compareTo(amount) > -1) {
						substitutePayConfigDTO = dto;
						break;
					}
				}
			}
			if (finalStatus.equals("YH_ERROR")) {
				failMsg = "银行类型错误，暂不支持此银行代付";
			}
			else {
				failMsg = "代付余额不足";
			}
		}
		if (substitutePayConfigDTO != null) {
			payOrderDTO.setChannelId(substitutePayConfigDTO.getId());
			payOrderDTO.setChannelCode(substitutePayConfigDTO.getChannelCode());
			payOrderDTO.setChannelName(substitutePayConfigDTO.getChannelName());
		}
		else {
			payOrderDTO.setChannelId(-1);
			payOrderDTO.setChannelCode("ERROR");
			payOrderDTO.setChannelName("没有可用代付通道");
			payOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			payOrderDTO.setFailReason(failMsg);
		}

		// 保存订单
		try {
			payOrderDTO.setFee(fee);
			MerchantPayOrder merchantPayOrder = BeanConvertUtils.convert(payOrderDTO, MerchantPayOrder.class);
			merchantPayOrderMapper.insertSelective(merchantPayOrder);
		} catch (Exception e) {
			LogPortal.error("{} 商户号:{} 发起代付，订单保存失败，发生{}异常", e, traceId, payOrderDTO.getMerchantId(), e.getClass().getName());
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，请联系技术支持，错误码:" + traceId);
			return commonResult;
		}
		if (substitutePayConfigDTO != null) {
			// 开始锁定可提现金额
			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付处理中可提现金额减少[" + totalTradeAmt + "]提现中的金额增加[" + payOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt.negate());
			merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount());
			changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "A");
			// 调用通道发起代付
			JSONObject inputParam = new JSONObject();
			// 商户系统内部订单号，要求64个字符内，只能是数字、大小写字母_-|* 且在同一个商户号下唯一
			inputParam.put("merchant_order_no", merchantOrderNo);
			// 订单总金额，单位为元
			inputParam.put("amount", amount);
			// 原账号数值 银行卡号或者支付宝账号
			// 必须进行AES加密，此数值是银行卡号或者支付宝账号
			inputParam.put("account_no", accountNo);
			// 账号名称 此数值是银行卡号或者支付宝账号对应的户名
			inputParam.put("account_name", payOrderDTO.getAccountName());

			// 交易描述，要求300个字符内，不能包含特殊字符:英文逗号，注意：下载对账单会返回此字段数据
			inputParam.put("description", payOrderDTO.getRemark());
			// 交易发起时间时间，格式为yyyyMMddHHmmss
			inputParam.put("apply_time", DateUtils.dateToIntegerst(currentDate, DateUtils.formatPattern_full_01));
			// 付款类型 0-银行卡 1-支付宝 2-爱游宝
			inputParam.put("account_type", payOrderDTO.getPayType());
			// 银行名称
			inputParam.put("bank_name", payOrderDTO.getBankName());
			inputParam.put("bank_city", payOrderDTO.getBankCity());
			inputParam.put("bank_province", payOrderDTO.getBankProvince());
			inputParam.put("channelCode", substitutePayConfigDTO.getChannelCode());
			inputParam.put("substitutePayConfigId", substitutePayConfigDTO.getId());
			inputParam.put("traceId", traceId);
			JSONObject channelResResult;
			try {
				channelResResult = channelHandleFactory.getHandler(inputParam.getString("channelCode")).orderCreate(inputParam);
				if (channelResResult == null) {
					commonResult.setCode(-1);
					commonResult.setMsg("代付提交失败，请联系技术支持，错误码:" + traceId);
					return commonResult;
				}
				String channelOrderNo = channelResResult.getString("channelOrderNo");
				Integer status = channelResResult.getInteger("status");
				String failReason = channelResResult.getString("failReason");
				if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(status)) {
					commonResult.setCode(-1);
					commonResult.setMsg("代付提交失败，原因:" + failReason + "，错误码:" + traceId);
				}
				status = status == null ? Integer.valueOf(1) : status;
				MerchantPayOrder merchantPayOrder = merchantPayOrderMapper.getMerchantPayOrderByMerchantOrderNo(merchantOrderNo);
				merchantPayOrder.setChannelOrderNo(channelOrderNo);
				merchantPayOrder.setStatus(status);
				merchantPayOrder.setFailReason(failReason);
				if (MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus().equals(status)) {
					merchantPayOrder.setQueryFlag(Integer.valueOf(1));
				}
				else if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(status)) {
					merchantAccountOptions = new MerchantAccountOptions();
					merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
					merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + payOrderDTO.getAmount() + "]");
					merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
					merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount().negate());
					changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "B");
				}
				else if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(status)) {
					merchantAccountOptions = new MerchantAccountOptions();
					merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
					merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + payOrderDTO.getAmount() + "]");
					merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount().negate());
					changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "B");
				}
				merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);
			} catch (Exception e) {
				LogPortal.error("{} 商户号:{} 发起代付，调用通道 发生{}异常", e, traceId, payOrderDTO.getMerchantId(), e.getClass().getName());
				commonResult.setCode(-1);
				commonResult.setMsg("代付提交失败，请联系技术支持，错误码:" + traceId);

				merchantAccountOptions = new MerchantAccountOptions();
				merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
				merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + payOrderDTO.getAmount() + "]");
				merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
				merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount().negate());
				changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "B");

				return commonResult;
			}
		}
		return commonResult;
	}

	/**
	 * 创建单个代付单子
	 *
	 * @author lch
	 * @date 2021/12/20
	 */
	private CommonResult createUserTransferPayOrder(MerchantDTO merchantDTO, MerchantPayOrderDTO payOrderDTO) {
		CommonResult commonResult = new CommonResult();
		commonResult.setCode(200);
		commonResult.setMsg("代付受理成功");
		String traceId = SnowFlakeUtils.getTraceId();

		//校验是否绑定了爱游宝
		aybUserTransferBind aybUserTransferBind = aybUserTransferBindService.getByMerchantId(merchantDTO.getId());
		ValidateUtil.businessValidate(aybUserTransferBind != null, "请先在三方支付配置中绑定爱游宝代付");

		// 代付手续费
		SettleConfigDTO settleConfigDTO = settleConfigService.getSettleConfig();
		if (settleConfigDTO.getMinPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMinPayAmount()) < 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额不能小于" + settleConfigDTO.getMinPayAmount() + "，错误码:" + traceId);
			return commonResult;
		}
		if (settleConfigDTO.getMaxPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMaxPayAmount()) > 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额不能大于" + settleConfigDTO.getMaxPayAmount() + "，错误码:" + traceId);
			return commonResult;
		}
		//手续费变成0
		BigDecimal fee = BigDecimal.ZERO;
		if (payOrderDTO.getAmount().compareTo(fee) <= 0) {
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，代付金额[" + payOrderDTO.getAmount() + "]必须大于手续费金额[" + fee + "]，错误码:" + traceId);
			return commonResult;
		}
		BigDecimal totalTradeAmt = payOrderDTO.getAmount();
		Date currentDate = DateUtils.getNowDate();
		String concat = DateUtils.dateToString(DateUtils.getNowDate(), DateUtils.formatPattern_full_03).concat(SnowFlakeUtils.getUniqueId());
		String merchantOrderNo = "DF".concat(concat);
		String accountNo = payOrderDTO.getAccountNo();
		payOrderDTO.setMerchantOrderNo(merchantOrderNo);
		payOrderDTO.setQueryFlag(Integer.valueOf(0)); //默认不开启查询
		payOrderDTO.setApplyDateIndex(DateUtils.dateToInteger(currentDate));
		payOrderDTO.setCreateTime(currentDate);
		payOrderDTO.setLastUpdateTime(currentDate);
		payOrderDTO.setApplyTime(currentDate);
		payOrderDTO.setStatus(MerchantPayOrderStatusEnum.WAIT_PAY.getStatus());

		// 查询代付通道接口
		BigDecimal amount = totalTradeAmt.subtract(fee);
		payOrderDTO.setChannelId(1);
		payOrderDTO.setChannelCode("ayb");
		payOrderDTO.setChannelName("爱游宝");

		// 保存订单
		try {
			payOrderDTO.setFee(fee);
			MerchantPayOrder merchantPayOrder = BeanConvertUtils.convert(payOrderDTO, MerchantPayOrder.class);
			merchantPayOrderMapper.insertSelective(merchantPayOrder);
		} catch (Exception e) {
			LogPortal.error("{} 商户号:{} 发起代付，订单保存失败，发生{}异常", e, traceId, payOrderDTO.getMerchantId(), e.getClass().getName());
			commonResult.setCode(-1);
			commonResult.setMsg("代付失败，请联系技术支持，错误码:" + traceId);
			return commonResult;
		}

		// 调用通道发起代付
		AybUserTransferOrderCreateReq req = new AybUserTransferOrderCreateReq();
		req.setTraceId(SnowFlakeUtils.getTraceId());
		req.setMerchantId(merchantDTO.getId());
		req.setMerchantOrderNo(payOrderDTO.getMerchantOrderNo());
		req.setPartitionName("--");
		req.setGameAccount("--");
		req.setPhone(merchantDTO.getPhone());
		req.setToGameAccount("--");
		req.setToName(payOrderDTO.getAccountName());
		req.setToPhone(payOrderDTO.getAccountNo());
		req.setAppliedAmount(payOrderDTO.getAmount());
		req.setFeeAmt(fee);
		req.setRemark(payOrderDTO.getRemark());
		req.setAppliedTime(DateUtils.getNowDate());

		JSONObject channelResResult;
		try {
			channelResResult = aybUserTransferHandler.createOrder(req);
			if (channelResResult == null) {
				commonResult.setCode(-1);
				commonResult.setMsg("【爱游宝代付下单】交失败，请联系技术支持，错误码:" + traceId);
				return commonResult;
			}
			String channelOrderNo = channelResResult.getString("channelOrderNo");
			Integer status = channelResResult.getInteger("status");
			String failReason = channelResResult.getString("failReason");
			if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(status)) {
				commonResult.setCode(-1);
				commonResult.setMsg("【爱游宝代付下单】失败，原因:" + failReason + "，错误码:" + traceId);
			}
			status = status == null ? Integer.valueOf(1) : status;
			MerchantPayOrder merchantPayOrder = merchantPayOrderMapper.getMerchantPayOrderByMerchantOrderNo(merchantOrderNo);
			merchantPayOrder.setChannelOrderNo(channelOrderNo);
			merchantPayOrder.setStatus(status);
			merchantPayOrder.setFailReason(failReason);
			if (MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus().equals(status)) {
				merchantPayOrder.setQueryFlag(Integer.valueOf(1));
			}
			merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);
		} catch (Exception e) {
			LogPortal.error("【爱游宝代付下单】{} 商户号:{} 发起代付，调用通道 发生{}异常", e, traceId, payOrderDTO.getMerchantId(), e.getClass().getName());
			commonResult.setCode(-1);
			commonResult.setMsg("【爱游宝代付下单】提交失败，请联系技术支持，错误码:" + traceId);
			return commonResult;
		}
		return commonResult;
	}

	/**
	 * 游戏代付单子
	 *
	 * @author lch
	 * @date 2021/12/20
	 */
	@Override
	public void createAybPayOrder(MerchantDTO merchantDTO, GamePlayerCashOrderDTO gameDto) {
		if (2 == gameDto.getPayType()) {
			createAybUserTransferPayOrder(merchantDTO, gameDto);
			return;
		}
		String traceId = SnowFlakeUtils.getTraceId();
		MerchantPayOrderDTO payOrderDTO = BeanConvertUtils.convert(gameDto, MerchantPayOrderDTO.class);
		payOrderDTO.setAmount(gameDto.getTransAmount());
		payOrderDTO.setBankName("爱游宝");
		payOrderDTO.setId(null);
		payOrderDTO.setAccountName(gameDto.getName());
		MerchantAccount merchantAccount = merchantAccountService.selectOne(gameDto.getMerchantId());
		BigDecimal cashWithdrawal = merchantAccount.getCashWithdrawal();
		// 可提现金额
		cashWithdrawal = cashWithdrawal == null ? BigDecimal.ZERO : cashWithdrawal;
		// 代付手续费
		SettleConfigDTO settleConfigDTO = settleConfigService.getSettleConfig();
		if (settleConfigDTO.getMinPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMinPayAmount()) < 0) {
			gameDto.setFailReason("代付失败，代付金额不能小于" + settleConfigDTO.getMinPayAmount() + "，错误码:" + traceId);
			gameDto.setStatus(AliOrderStatus.FAIL.getCode());
			gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			return;
		}
		if (settleConfigDTO.getMaxPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMaxPayAmount()) > 0) {
			gameDto.setFailReason("代付失败，代付金额不能大于" + settleConfigDTO.getMaxPayAmount() + "，错误码:" + traceId);
			gameDto.setStatus(AliOrderStatus.FAIL.getCode());
			gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			return;
		}
		BigDecimal fee = MerchantSettleServiceChargeUtil.getServiceCharge(gameDto.getMerchantId(), payOrderDTO.getAmount(), settleConfigDTO.getPayFeeCustom());
		if (cashWithdrawal.compareTo((payOrderDTO.getAmount().add(fee))) < 0) {
			gameDto.setFailReason("代付失败，代付金额[" + payOrderDTO.getAmount() + "]+代付手续费[" + fee + "]大于可提现金额[" + cashWithdrawal + "]，错误码:" + traceId);
			gameDto.setStatus(AliOrderStatus.FAIL.getCode());
			gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			return;
		}
		BigDecimal amount = payOrderDTO.getAmount();
		Date currentDate = DateUtils.getNowDate();
		String accountNo = payOrderDTO.getAccountNo();
		payOrderDTO.setQueryFlag(0); //默认不开启查询
		payOrderDTO.setApplyDateIndex(DateUtils.dateToInteger(currentDate));
		payOrderDTO.setCreateTime(currentDate);
		payOrderDTO.setLastUpdateTime(currentDate);
		payOrderDTO.setApplyTime(currentDate);
		payOrderDTO.setStatus(MerchantPayOrderStatusEnum.WAIT_PAY.getStatus());

		// 查询代付通道接口
		SubstitutePayConfigDTO substitutePayConfigDTO = null;
		BigDecimal totalTradeAmt = amount.add(fee);

		SubstitutePayCriteria substitutePayCriteria = new SubstitutePayCriteria();
		substitutePayCriteria.setChannelType(payOrderDTO.getPayType());
		substitutePayCriteria.setChannelStatus(1);
		List<SubstitutePayConfigDTO> list = substitutePayConfigService.getListSubstitutePayConfigByChannelCode(substitutePayCriteria);
		String failMsg = "";
		if (!CollectionUtils.isEmpty(list)) {
			String finalStatus = "YH_ERROR";
			JSONObject balanceParam = new JSONObject();
			// 商户系统内部订单号，要求64个字符内，只能是数字、大小写字母_-|* 且在同一个商户号下唯一
			balanceParam.put("traceId", traceId);
			balanceParam.put("bankName", payOrderDTO.getBankName());
			for (SubstitutePayConfigDTO dto : list) {
				balanceParam.put("substitutePayConfigId", dto.getId());
				JSONObject balanceQuery = channelHandleFactory.getHandler(dto.getChannelCode()).balanceQuery(balanceParam);
				Integer status = balanceQuery.getInteger("status");
				if (status == 1) {
					finalStatus = "YE_ERROR";
					BigDecimal balance = balanceQuery.getBigDecimal("balance");
					if (balance.compareTo(amount) > -1) {
						substitutePayConfigDTO = dto;
						break;
					}
				}
			}
			if (finalStatus.equals("YH_ERROR")) {
				failMsg = "银行类型错误，暂不支持此银行代付";
			}
			else {
				failMsg = "代付余额不足";
			}
		}
		if (substitutePayConfigDTO != null) {
			payOrderDTO.setChannelId(substitutePayConfigDTO.getId());
			payOrderDTO.setChannelCode(substitutePayConfigDTO.getChannelCode());
			payOrderDTO.setChannelName(substitutePayConfigDTO.getChannelName());
		}
		else {
			payOrderDTO.setChannelId(-1);
			payOrderDTO.setChannelCode("ERROR");
			payOrderDTO.setChannelName("没有可用代付通道");
			payOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			payOrderDTO.setFailReason(failMsg);
		}

		// 保存订单
		payOrderDTO.setFee(fee);
		MerchantPayOrder merchantPayOrder = BeanConvertUtils.convert(payOrderDTO, MerchantPayOrder.class);
		merchantPayOrder.setOrderSource(2);
		merchantPayOrderMapper.insertSelective(merchantPayOrder);

		gameDto.setFailReason(merchantPayOrder.getFailReason());
		gameDto.setStatus(payOrderDTO.getStatus());
		gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);

		if (substitutePayConfigDTO != null) {
			// 开始锁定可提现金额
			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付处理中可提现金额减少[" + totalTradeAmt + "]提现中的金额增加[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt.negate());
			merchantAccountOptions.setCashWithdrawalIng(totalTradeAmt);
			changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "A");
			// 调用通道发起代付
			JSONObject inputParam = new JSONObject();
			// 商户系统内部订单号，要求64个字符内，只能是数字、大小写字母_-|* 且在同一个商户号下唯一
			inputParam.put("merchant_order_no", gameDto.getMerchantOrderNo());
			// 订单总金额，单位为元
			inputParam.put("amount", amount);
			// 原账号数值 银行卡号或者支付宝账号
			// 必须进行AES加密，此数值是银行卡号或者支付宝账号
			inputParam.put("account_no", accountNo);
			// 账号名称 此数值是银行卡号或者支付宝账号对应的户名
			inputParam.put("account_name", payOrderDTO.getAccountName());

			// 交易描述，要求300个字符内，不能包含特殊字符:英文逗号，注意：下载对账单会返回此字段数据
			inputParam.put("description", payOrderDTO.getRemark());
			// 交易发起时间时间，格式为yyyyMMddHHmmss
			inputParam.put("apply_time", DateUtils.dateToIntegerst(currentDate, DateUtils.formatPattern_full_01));
			// 付款类型 0-银行卡 1-支付宝 2-爱游宝
			inputParam.put("account_type", payOrderDTO.getPayType());
			// 银行名称
			inputParam.put("bank_name", "爱游宝");
			inputParam.put("bank_city", payOrderDTO.getBankCity());
			inputParam.put("bank_province", payOrderDTO.getBankProvince());
			inputParam.put("channelCode", substitutePayConfigDTO.getChannelCode());
			inputParam.put("substitutePayConfigId", substitutePayConfigDTO.getId());
			inputParam.put("traceId", traceId);
			JSONObject channelResResult;
			try {
				channelResResult = channelHandleFactory.getHandler(inputParam.getString("channelCode")).orderCreate(inputParam);
				if (channelResResult == null) {
					gameDto.setFailReason("代付提交失败，请联系技术支持，错误码:" + traceId);
					gameDto.setStatus(AliOrderStatus.FAIL.getCode());
					gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
					return;
				}
				String channelOrderNo = channelResResult.getString("channelOrderNo");
				Integer status = channelResResult.getInteger("status");
				String failReason = channelResResult.getString("failReason");
				status = status == null ? Integer.valueOf(1) : status;
				MerchantPayOrder tempMerchantPayOrder = merchantPayOrderMapper.getMerchantPayOrderByMerchantOrderNo(gameDto.getMerchantOrderNo());
				tempMerchantPayOrder.setChannelOrderNo(channelOrderNo);
				tempMerchantPayOrder.setStatus(status);
				tempMerchantPayOrder.setFailReason(failReason);
				if (MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus().equals(status)) {
					tempMerchantPayOrder.setQueryFlag(1);
				}
				else if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(status)) {
					merchantAccountOptions = new MerchantAccountOptions();
					merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
					merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + totalTradeAmt + "]");
					merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
					merchantAccountOptions.setCashWithdrawalIng(totalTradeAmt.negate());
					changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "B");
				}
				merchantPayOrderMapper.updateByPrimaryKeySelective(tempMerchantPayOrder);
				gameDto.setFailReason(tempMerchantPayOrder.getFailReason());
				gameDto.setStatus(tempMerchantPayOrder.getStatus());
				gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			} catch (Exception e) {
				LogPortal.error("{} 商户号:{} 发起代付，调用通道 发生{}异常", e, traceId, payOrderDTO.getMerchantId(), e.getClass().getName());

				merchantAccountOptions = new MerchantAccountOptions();
				merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
				merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + payOrderDTO.getAmount() + "]");
				merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
				merchantAccountOptions.setCashWithdrawalIng(totalTradeAmt.negate());
				changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "B");

				gameDto.setFailReason("代付提交失败，请联系技术支持，错误码:" + traceId);
				gameDto.setStatus(AliOrderStatus.FAIL.getCode());
				gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			}
		}
	}

	private void createAybUserTransferPayOrder(MerchantDTO merchantDTO, GamePlayerCashOrderDTO gameDto) {
		log.info("单个代付gameDto:{}", JSONObject.toJSONString(gameDto));

		//校验是否绑定了爱游宝
		aybUserTransferBind aybUserTransferBind = aybUserTransferBindService.getByMerchantId(merchantDTO.getId());
		ValidateUtil.businessValidate(aybUserTransferBind != null, "请先在三方支付配置中绑定爱游宝代付");

		String traceId = SnowFlakeUtils.getTraceId();
		//重新生成一个商户订单号
		gameDto.setMerchantOrderNo("GT" + SnowFlakeUtils.getTraceId());
		MerchantPayOrderDTO payOrderDTO = BeanConvertUtils.convert(gameDto, MerchantPayOrderDTO.class);
		payOrderDTO.setAmount(gameDto.getTransAmount());
		payOrderDTO.setBankName("爱游宝");
		payOrderDTO.setId(null);
		payOrderDTO.setAccountName(gameDto.getName());
		// 代付手续费
		SettleConfigDTO settleConfigDTO = settleConfigService.getSettleConfig();
		if (settleConfigDTO.getMinPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMinPayAmount()) < 0) {
			gameDto.setFailReason("【爱游宝代付下单】失败，代付金额不能小于" + settleConfigDTO.getMinPayAmount() + "，错误码:" + traceId);
			gameDto.setStatus(AliOrderStatus.FAIL.getCode());
			gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			return;
		}
		if (settleConfigDTO.getMaxPayAmount() != null && payOrderDTO.getAmount().compareTo(settleConfigDTO.getMaxPayAmount()) > 0) {
			gameDto.setFailReason("【爱游宝代付下单】失败，代付金额不能大于" + settleConfigDTO.getMaxPayAmount() + "，错误码:" + traceId);
			gameDto.setStatus(AliOrderStatus.FAIL.getCode());
			gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			return;
		}
		BigDecimal fee = BigDecimal.ZERO;
		BigDecimal amount = payOrderDTO.getAmount();
		Date currentDate = DateUtils.getNowDate();
		String accountNo = payOrderDTO.getAccountNo();
		payOrderDTO.setQueryFlag(0); //默认不开启查询
		payOrderDTO.setApplyDateIndex(DateUtils.dateToInteger(currentDate));
		payOrderDTO.setCreateTime(currentDate);
		payOrderDTO.setLastUpdateTime(currentDate);
		payOrderDTO.setApplyTime(currentDate);
		payOrderDTO.setStatus(MerchantPayOrderStatusEnum.WAIT_PAY.getStatus());

		// 查询代付通道接口
		BigDecimal totalTradeAmt = amount.add(fee);
		payOrderDTO.setChannelId(1);
		payOrderDTO.setChannelCode("ayb");
		payOrderDTO.setChannelName("爱游宝");

		// 保存订单
		payOrderDTO.setFee(fee);
		MerchantPayOrder merchantPayOrder = BeanConvertUtils.convert(payOrderDTO, MerchantPayOrder.class);
		merchantPayOrder.setOrderSource(2);
		merchantPayOrderMapper.insertSelective(merchantPayOrder);

		gameDto.setFailReason(merchantPayOrder.getFailReason());
		gameDto.setStatus(payOrderDTO.getStatus());
		gamePlayerCashOrderService.updateById(gameDto);

		// 调用通道发起代付
		AybUserTransferOrderCreateReq req = new AybUserTransferOrderCreateReq();
		req.setTraceId(SnowFlakeUtils.getTraceId());
		req.setMerchantId(merchantDTO.getId());
		req.setMerchantOrderNo(payOrderDTO.getMerchantOrderNo());
		req.setPartitionName(gameDto.getPartitionName());
		req.setGameAccount("--");
		req.setToGameAccount(gameDto.getGameAccount());
		req.setToName(gameDto.getName());
		req.setToPhone(gameDto.getAccountNo());
		req.setAppliedAmount(gameDto.getApplyAmount());
		req.setFeeAmt(gameDto.getFee());
		req.setRemark(payOrderDTO.getRemark());
		req.setAppliedTime(DateUtils.getNowDate());

		JSONObject channelResResult;
		try {
			channelResResult = aybUserTransferHandler.createOrder(req);
			if (channelResResult == null) {
				gameDto.setFailReason("【爱游宝代付下单】提交失败，请联系技术支持，错误码:" + traceId);
				gameDto.setStatus(AliOrderStatus.CREAT.getCode());
				gamePlayerCashOrderService.updateById(gameDto);
				return;
			}
			String channelOrderNo = channelResResult.getString("channelOrderNo");
			Integer status = channelResResult.getInteger("status");
			String failReason = channelResResult.getString("failReason");
			status = status == null ? Integer.valueOf(1) : status;
			MerchantPayOrder tempMerchantPayOrder = merchantPayOrderMapper.getMerchantPayOrderByMerchantOrderNo(gameDto.getMerchantOrderNo());
			tempMerchantPayOrder.setChannelOrderNo(channelOrderNo);
			tempMerchantPayOrder.setStatus(status);
			tempMerchantPayOrder.setFailReason(failReason);
			if (MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus().equals(status)) {
				tempMerchantPayOrder.setQueryFlag(1);
				gameDto.setStatus(tempMerchantPayOrder.getStatus());
			}
			else if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(status)) {
				gameDto.setStatus(AliOrderStatus.CREAT.getCode());
			}
			merchantPayOrderMapper.updateByPrimaryKeySelective(tempMerchantPayOrder);
			gameDto.setFailReason(tempMerchantPayOrder.getFailReason());
			gamePlayerCashOrderService.updateById(gameDto);
		} catch (Exception e) {
			LogPortal.error("【爱游宝代付下单】{} 商户号:{} 发起代付，调用通道 发生{}异常", e, traceId, payOrderDTO.getMerchantId(), e.getClass().getName());
			gameDto.setFailReason("【爱游宝代付下单】提交失败，请联系技术支持，错误码:" + traceId);
			gameDto.setStatus(AliOrderStatus.CREAT.getCode());
			gamePlayerCashOrderService.updateById(gameDto);
		}
	}

	@Override
	public JSONObject orderQuery(JSONObject inputParam) {
		return channelService.orderQuery(inputParam);
	}

	@Override
	public PageInfoDTO<MerchantPayOrderDTO> getMerchantPayOrderListByPage(MerchantPayOrderCriteria merchantPayOrderCriteria) {
		PageHelper.startPage(merchantPayOrderCriteria.getPageNum(), merchantPayOrderCriteria.getPageSize());
		List<MerchantPayOrderDTO> merchantPayOrderDTOList = merchantPayOrderMapper.getMerchantPayOrderListByPage(merchantPayOrderCriteria);
		if (!CollectionUtils.isEmpty(merchantPayOrderDTOList)) {
			merchantPayOrderDTOList.forEach(item -> {
				item.setAccountName(SensitiveDataUtil.accountNameDesensitization(item.getAccountName()));
				if (item.getPayType() == 0) {
					item.setAccountNo(SensitiveDataUtil.cardNoDesensitization(item.getAccountNo()));
				}
				else { // 支付宝
					item.setAccountNo(SensitiveDataUtil.alipayAccountNoDesensitization(item.getAccountNo()));
				}
			});
		}
		else {
			merchantPayOrderDTOList = new ArrayList<>();
		}
		PageInfo<MerchantPayOrderDTO> pageInfo = new PageInfo<>(merchantPayOrderDTOList);
		PageInfoDTO<MerchantPayOrderDTO> pageDTO = new PageInfoDTO<>();
		pageDTO.setTotal(pageInfo.getTotal());
		pageDTO.setPageSize(pageInfo.getPageSize());
		pageDTO.setPageNum(pageInfo.getPageNum());
		pageDTO.setList(merchantPayOrderDTOList);
		return pageDTO;
	}

	@Override
	public MerchantPayOrderDTO getMerchantPayOrderByMerchantOrderNo(String orderId) {
		return BeanConvertUtils.convert(merchantPayOrderMapper.getMerchantPayOrderByMerchantOrderNo(orderId), MerchantPayOrderDTO.class);
	}

	@Override
	public boolean payNotify(String traceId, String requestBody, String sign) {
		JSONObject plcyObject = JSONObject.parseObject(requestBody);
		JSONObject dataObject = JSONObject.parseObject(plcyObject.getString("data"));
		String orderId = dataObject.getString("merchant_order_no");
		if (StringUtils.isEmpty(orderId)) {
			LogPortal.info("{} 支付平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		String channelOrderStatus = dataObject.getString("status");
		if (!"FAIL".equals(channelOrderStatus) && !"SUCCESS".equals(channelOrderStatus)) {
			LogPortal.info("{} 支付平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderId, channelOrderStatus);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderId);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 支付平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderId);
			return true;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 支付平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderId, merchantPayOrderDTO.getStatus(), channelOrderStatus);
			return true;
		}

		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		boolean result = RSA.verify(requestBody, sign, substitutePayConfigDTO.getEhbPayConfigParamVO().getChannelPubKey());
		if (result) {
			Date currentDate = DateUtils.getNowDate();
			if ("SUCCESS".equals(channelOrderStatus)) {
				merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
				merchantPayOrderDTO.setQueryFlag(0);
				merchantPayOrderDTO.setFinishTime(currentDate);

				MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
				BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
				merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
				merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
				merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
				changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
			}
			else if ("FAIL".equals(channelOrderStatus)) {
				merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
				merchantPayOrderDTO.setQueryFlag(0);
				merchantPayOrderDTO.setFinishTime(currentDate);
				String failReason = dataObject.getString("err_code_desc");
				if (StringUtils.isEmpty(failReason)) {
					failReason = dataObject.getString("return_msg");
				}
				merchantPayOrderDTO.setFailReason(failReason);

				MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
				BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
				merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
				merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
				merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
				merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
				changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			}
			merchantPayOrderDTO.setLastUpdateTime(currentDate);
			merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
			if (merchantPayOrderDTO.getOrderSource() != null && merchantPayOrderDTO.getOrderSource() == 2) {
				GamePlayerCashOrderDTO gameDto = new GamePlayerCashOrderDTO();
				gameDto.setMerchantOrderNo(merchantPayOrderDTO.getMerchantOrderNo());
				gameDto.setStatus(merchantPayOrderDTO.getStatus());
				if (gameDto.getStatus() == 2) {
					gameDto.setFinishTime(currentDate);
					gameDto.setFailReason("付款成功");
				}
				LogPortal.info("{} 玩家提现订单回调成功：{} 开始执行状态修改 {}", traceId, JSONObject.toJSONString(gameDto));
				gamePlayerCashOrderService.updateByMerChantOrderNo(gameDto);
			}
		}
		return true;
	}

	@Override
	public boolean WanXPayNotify(String traceId, String status, String orderId) {
		if (StringUtils.isEmpty(orderId)) {
			LogPortal.info("{} 万象平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		if (!"3".equals(status) && !"2".equals(status)) {
			LogPortal.info("{} 万象平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderId, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderId);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 万象平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderId);
			return true;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 万象平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderId, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("2".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else if ("3".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean LongBaoPayNotify(String traceId, String status, String orderId, String desc) {
		if (StringUtils.isEmpty(orderId)) {
			LogPortal.info("{} 龙宝平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		if (!"S".equals(status) && !"F".equals(status)) {
			LogPortal.info("{} 龙宝平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderId, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderId);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 龙宝平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderId);
			return true;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 龙宝平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderId, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("S".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else if ("F".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);
			merchantPayOrderDTO.setFailReason(desc);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean ZhuoFuTongPayNotify(String traceId, String status, String orderNo, String desc) {
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 卓付通平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		if (!"SUCCESS".equals(status) && !"FAILED".equals(status)) {
			LogPortal.info("{} 卓付通平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 卓付通平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 卓付通平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("SUCCESS".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else if ("FAILED".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);
			merchantPayOrderDTO.setFailReason(desc);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public int getTotalCount(MerchantPayOrderDTO dto) {
		Example example = new Example(MerchantPayOrder.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo(MerchantPayOrder.Fields.status, dto.getStatus());
		criteria.andEqualTo(MerchantPayOrder.Fields.queryFlag, dto.getQueryFlag());
		if (StringUtils.isNotBlank(dto.getNotChannelCode())) {
			criteria.andNotEqualTo(MerchantPayOrder.Fields.channelCode, dto.getNotChannelCode());
		}
		return merchantPayOrderMapper.selectCountByExample(example);
	}

	@Override
	public List<MerchantPayOrderDTO> getProcessingMerchantPayOrderList(MerchantPayOrderDTO dto) {
		Example example = new Example(MerchantPayOrder.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo(MerchantPayOrder.Fields.status, dto.getStatus());
		criteria.andEqualTo(MerchantPayOrder.Fields.queryFlag, dto.getQueryFlag());
		if (StringUtils.isNotBlank(dto.getNotChannelCode())) {
			criteria.andNotEqualTo(MerchantPayOrder.Fields.channelCode, dto.getNotChannelCode());
		}
		List<MerchantPayOrder> list = merchantPayOrderMapper.selectByExample(example);
		if (CollectionUtils.isEmpty(list)) {
			return Lists.newLinkedList();
		}
		return BeanConvertUtils.convert(list, MerchantPayOrderDTO.class);
	}

	@Override
	public void updateMerchantPayOrder(MerchantPayOrderDTO dto) {
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(dto.getStatus())) {
			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = dto.getAmount();
			merchantAccountOptions.setMerchantId(dto.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + dto.getMerchantOrderNo() + "代付成功提现中的金额减少[" + dto.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(dto.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, dto.getMerchantOrderNo(), "C");
		}
		else if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(dto.getStatus())) {
			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = dto.getAmount();
			merchantAccountOptions.setMerchantId(dto.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + dto.getMerchantOrderNo() + " 代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + dto.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(dto.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, dto.getMerchantOrderNo(), "B");
		}
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(dto, MerchantPayOrder.class));
	}

	@Override
	public void changeMerchantAccountAmt(MerchantAccountOptions merchantAccountOptions, String merchantOrderNo, String businessFlag) {
		String lockName = getClass().getName().concat(".changeMerchantAccountAmt-").concat(merchantOrderNo).concat("-").concat(businessFlag).concat(System.getenv("XY_GAME_PAY_LOCK_FLAG"));
		boolean lock = false;
		try {
			if (lock = distributedLock.getLock(lockName)) {
				if (!redisCacheUtil.hasKey(lockName)) {
					redisCacheUtil.setObjectToCacheDelaySeconds(lockName, 1, 60L);
					merchantAccountService.updateMerchantAccount(merchantAccountOptions);
				}
			}
		} catch (GetLockFailedException e) {
			LogPortal.error("[DISTRIBUTED_LOCK_ACQUIRE_FAILED_ZK] 分布式锁获取失败,锁名称为:{}", lockName);
		} finally {
			if (lock) {
				try {
					distributedLock.releaseLock(lockName);
				} catch (ReleaseLockFailedException e) {
					LogPortal.error("[DISTRIBUTED_LOCK_RELEASE_FAILED_ZK] 分布式锁释放失败,锁名称为:{}", lockName);
				}
			}
		}
	}

	@Override
	public Map<Integer, Map<String, Object>> selectSumPay(OrderInfoCriteria cri) {
		return merchantPayOrderMapper.selectSumPay(cri);
	}

	@Override
	public CheckUploadPayOrderDTO checkData(Integer merchantId, String batchPayFileId, List<UploadPayOrderData> dataList) {
		// 代付手续费
		SettleConfigDTO settleConfigDTO = settleConfigService.getSettleConfig();
		//校验是否绑定了爱游宝
		aybUserTransferBind aybUserTransferBind = aybUserTransferBindService.getByMerchantId(merchantId);

		List<MerchantBatchPayFileFailReason> failList = new ArrayList<>();
		List<MerchantPayOrder> successList = new ArrayList<>();
		BigDecimal sum = BigDecimal.ZERO;
		for (int i = 0; i < dataList.size(); i++) {
			boolean boo = true;
			MerchantPayOrder payOrder = new MerchantPayOrder();
			UploadPayOrderData data = dataList.get(i);
			payOrder.setRemark(data.getRemark());
			if (StringUtils.isBlank(data.getAccountNo())) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailPosition("第" + (i + 2) + "行");
				failReason.setFailDescription("收款账号不能为空");
				failList.add(failReason);
				boo = false;
			}
			else {
				payOrder.setAccountNo(data.getAccountNo());
			}
			if (StringUtils.isBlank(data.getAccountName())) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailPosition("第" + (i + 2) + "行");
				failReason.setFailDescription("户名不能为空");
				failList.add(failReason);
				boo = false;
			}
			else {
				payOrder.setAccountName(data.getAccountName());
			}
			if (data.getAmount() == null) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailPosition("第" + (i + 2) + "行");
				failReason.setFailDescription("付款金额不能为空");
				failList.add(failReason);
				boo = false;
			}
			else {
				if (data.getAmount().compareTo(BigDecimal.ZERO) <= 0) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("代付金额必须大于0元");
					failList.add(failReason);
					boo = false;
				}
				else {
					BigDecimal fee = MerchantSettleServiceChargeUtil.getServiceCharge(merchantId, data.getAmount(), settleConfigDTO.getPayFeeCustom());
					if (data.getAmount().compareTo(fee) < 0) {
						MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
						failReason.setId(SnowFlakeUtils.getUniqueId());
						failReason.setBatchPayFileId(batchPayFileId);
						failReason.setFailPosition("第" + (i + 2) + "行");
						failReason.setFailDescription("代付金额不能小于手续费" + fee + "元");
						failList.add(failReason);
						boo = false;
					}
					else {
						payOrder.setAmount(data.getAmount());
						payOrder.setFee(fee);
						if (!"爱游宝".equals(data.getTag())) {
							sum = sum.add(data.getAmount());
						}
					}
				}
			}
			if (StringUtils.isEmpty(data.getTag())) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailPosition("第" + (i + 2) + "行");
				failReason.setFailDescription("账户类型不能为空");
				failList.add(failReason);
				boo = false;
			}
			else if ("支付宝".equals(data.getTag())) {
				payOrder.setPayType(1);
				payOrder.setBankName("支付宝");
				if (!(CheckUtils.checkPhone(data.getAccountNo()) || CheckUtils.checkEmail(data.getAccountNo()))) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("支付宝账号格式错误");
					failList.add(failReason);
					boo = false;
				}
			}
			else if ("银行卡".equals(data.getTag())) {
				if (!Validator.isNumber(data.getAccountNo())) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("银行卡账号格式错误");
					failList.add(failReason);
					boo = false;
				}
				payOrder.setPayType(0);
				if (StringUtils.isBlank(data.getBankName())) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("银行名称不能为空");
					failList.add(failReason);
					boo = false;
				}
				else {
					payOrder.setBankName(data.getBankName());
				}
				if (StringUtils.isBlank(data.getBankProvince())) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("开户省不能为空");
					failList.add(failReason);
					boo = false;
				}
				else {
					payOrder.setBankProvince(data.getBankProvince());
				}
				if (StringUtils.isBlank(data.getBankCity())) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("开户城市不能为空");
					failList.add(failReason);
					boo = false;
				}
				else {
					payOrder.setBankCity(data.getBankCity());
				}
			}
			else if ("爱游宝".equals(data.getTag())) {
				payOrder.setPayType(2);
				payOrder.setBankName("爱游宝");
				if (!(CheckUtils.checkPhone(data.getAccountNo()))) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("爱游宝账号格式错误，只支持合法的手机号");
					failList.add(failReason);
					boo = false;
				}
				if (aybUserTransferBind == null) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("请先在三方支付配置中绑定爱游宝代付");
					failList.add(failReason);
					boo = false;
				}
				if (StringUtils.isEmpty(data.getRemark())) {
					MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
					failReason.setId(SnowFlakeUtils.getUniqueId());
					failReason.setBatchPayFileId(batchPayFileId);
					failReason.setFailPosition("第" + (i + 2) + "行");
					failReason.setFailDescription("账户类型为爱游宝，付款描述不能为空，请填写游戏名称");
					failList.add(failReason);
					boo = false;
				}
			}
			else {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailPosition("第" + (i + 2) + "行");
				failReason.setFailDescription("账户类型错误");
				failList.add(failReason);
				boo = false;
			}
			if (boo) {
				payOrder.setId(SnowFlakeUtils.getUniqueId());
				String concat =
						DateUtils.dateToString(DateUtils.getNowDate(), DateUtils.formatPattern_full_03).concat(SnowFlakeUtils.getUniqueId());
				String merchantOrderNo = "PF".concat(concat);
				payOrder.setMerchantOrderNo(merchantOrderNo);
				payOrder.setMerchantId(merchantId);
				payOrder.setQueryFlag(0);
				Date date = new Date();
				payOrder.setApplyTime(date);
				payOrder.setApplyDateIndex(DateUtils.dateToInteger(date));
				payOrder.setStatus(0);
				successList.add(payOrder);
			}
		}
		MerchantAccount merchantAccount = merchantAccountService.selectOne(merchantId);
		if (merchantAccount == null) {
			throw new ParameterException("非法商户");
		}
		else {
			BigDecimal cashWithdrawal = merchantAccount.getCashWithdrawal();
			// 可提现金额
			cashWithdrawal = cashWithdrawal == null ? BigDecimal.ZERO : cashWithdrawal;

			if (settleConfigDTO.getMinPayAmount() != null && sum.compareTo(settleConfigDTO.getMinPayAmount()) < 0) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailDescription("代付失败，代付金额不能小于" + settleConfigDTO.getMinPayAmount());
				failList.add(failReason);
			}
			if (settleConfigDTO.getMaxPayAmount() != null && sum.compareTo(settleConfigDTO.getMaxPayAmount()) > 0) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailDescription("代付失败，代付金额不能大于" + settleConfigDTO.getMaxPayAmount());
				failList.add(failReason);
			}
			if (sum.compareTo(cashWithdrawal) > 0) {
				MerchantBatchPayFileFailReason failReason = new MerchantBatchPayFileFailReason();
				failReason.setId(SnowFlakeUtils.getUniqueId());
				failReason.setBatchPayFileId(batchPayFileId);
				failReason.setFailDescription("代付失败，代付总金额[" + sum + "]大于可提现金额[" + cashWithdrawal + "]");
				failList.add(failReason);
			}
		}
		return new CheckUploadPayOrderDTO(successList, failList, sum);
	}

	@Override
	public boolean bathAddPay(String batchNo, List<MerchantPayOrder> successList, List<MerchantBatchPayFileFailReason> failList, MerchantBatchPayFile merchantBatchPayFile) {
		int batchSize = 200;
		if (!CollectionUtils.isEmpty(failList)) {
			merchantBatchPayFile.setStatus(1);
			int num = failList.size() % batchSize == 0 ? failList.size() / batchSize : failList.size() / batchSize + 1;
			for (int i = 0; i < num; i++) {
				List<MerchantBatchPayFileFailReason> subList = failList.subList(i * batchSize, i == num - 1 ? failList.size() :
						(i + 1) * batchSize);
				merchantBatchPayFileFailReasonMapper.batchAddFailReason(subList);
			}
		}
		else if (!CollectionUtils.isEmpty(successList)) {
			merchantBatchPayFile.setStatus(2);
			int num = successList.size() % batchSize == 0 ? successList.size() / batchSize : successList.size() / batchSize + 1;
			for (int i = 0; i < num; i++) {
				List<MerchantPayOrder> subList = successList.subList(i * batchSize, i == num - 1 ? successList.size() :
						(i + 1) * batchSize);
				merchantPayOrderMapper.bathAddPay(subList);
				merchantBatchAndPayMapper.batchAdd(batchNo, subList);
			}
		}
		merchantBatchPayFileService.updatePayFile(merchantBatchPayFile);
		return true;
	}

	@Override
	public boolean add(MerchantBatchPayFile merchantBatchPayFile) {
		return merchantBatchPayFileService.add(merchantBatchPayFile);
	}

	@Override
	public List<MerchantPayOrderDTO> selectBatchPayInfo(Integer status) {
		return merchantPayOrderMapper.selectBatchPayOrder(status);
	}

	/**
	 * 批量代付
	 *
	 * @author lch
	 * @date 2021/12/11
	 */
	@Override
	public boolean createBathPayOrder(MerchantPayOrderDTO payOrderDTO) {
		//爱游宝
		if (payOrderDTO.getPayType() == 2) {
			return createBathUserTransferPayOrder(payOrderDTO);
		}

		//银行卡
		String traceId = SnowFlakeUtils.getTraceId();
		BigDecimal totalTradeAmt = payOrderDTO.getAmount();

		// 查询代付通道接口
		SubstitutePayConfigDTO substitutePayConfigDTO = null;
		BigDecimal amount = totalTradeAmt.subtract(payOrderDTO.getFee());

		SubstitutePayCriteria substitutePayCriteria = new SubstitutePayCriteria();
		substitutePayCriteria.setChannelType(payOrderDTO.getPayType());
		substitutePayCriteria.setChannelStatus(1);
		List<SubstitutePayConfigDTO> list = substitutePayConfigService.getListSubstitutePayConfigByChannelCode(substitutePayCriteria);
		String failMsg = "没有可用的代付渠道";
		if (!CollectionUtils.isEmpty(list)) {
			String finalStatus = "YH_ERROR";
			JSONObject balanceParam = new JSONObject();
			balanceParam.put("traceId", traceId);
			balanceParam.put("bankName", payOrderDTO.getBankName());
			for (SubstitutePayConfigDTO dto : list) {
				balanceParam.put("substitutePayConfigId", dto.getId());
				JSONObject balanceQuery = channelHandleFactory.getHandler(dto.getChannelCode()).balanceQuery(balanceParam);
				Integer status = balanceQuery.getInteger("status");
				if (status == 1) {
					finalStatus = "YE_ERROR";
					BigDecimal balance = balanceQuery.getBigDecimal("balance");
					if (balance.compareTo(amount) > -1) {
						substitutePayConfigDTO = dto;
						break;
					}
				}
			}
			if (finalStatus.equals("YH_ERROR")) {
				failMsg = "银行类型错误，暂不支持此银行代付";
			}
			else {
				failMsg = "代付余额不足";
			}
		}

		MerchantPayOrder merchantPayOrder = new MerchantPayOrder();
		merchantPayOrder.setId(payOrderDTO.getId());

		if (substitutePayConfigDTO != null) {
			merchantPayOrder.setChannelId(substitutePayConfigDTO.getId());
			merchantPayOrder.setChannelCode(substitutePayConfigDTO.getChannelCode());
			merchantPayOrder.setChannelName(substitutePayConfigDTO.getChannelName());
			merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);

			// 调用通道发起代付
			JSONObject inputParam = new JSONObject();
			// 商户系统内部订单号，要求64个字符内，只能是数字、大小写字母_-|* 且在同一个商户号下唯一
			inputParam.put("merchant_order_no", payOrderDTO.getMerchantOrderNo());
			// 订单总金额，单位为元
			inputParam.put("amount", amount);
			// 原账号数值 银行卡号或者支付宝账号
			// 必须进行AES加密，此数值是银行卡号或者支付宝账号
			inputParam.put("account_no", payOrderDTO.getAccountNo());
			// 账号名称 此数值是银行卡号或者支付宝账号对应的户名
			inputParam.put("account_name", payOrderDTO.getAccountName());

			// 交易描述，要求300个字符内，不能包含特殊字符:英文逗号，注意：下载对账单会返回此字段数据
			inputParam.put("description", payOrderDTO.getRemark());
			// 交易发起时间时间，格式为yyyyMMddHHmmss
			inputParam.put("apply_time", DateUtils.dateToIntegerst(new Date(), DateUtils.formatPattern_full_01));
			// 付款类型 0-银行卡 1-支付宝 2-爱游宝
			inputParam.put("account_type", payOrderDTO.getPayType());
			// 银行名称
			inputParam.put("bank_name", payOrderDTO.getBankName());
			inputParam.put("bank_city", payOrderDTO.getBankCity());
			inputParam.put("bank_province", payOrderDTO.getBankProvince());
			inputParam.put("channelCode", substitutePayConfigDTO.getChannelCode());
			inputParam.put("substitutePayConfigId", substitutePayConfigDTO.getId());
			inputParam.put("traceId", traceId);
			JSONObject channelResResult;
			try {
				channelResResult = channelHandleFactory.getHandler(inputParam.getString("channelCode")).orderCreate(inputParam);
				if (channelResResult == null) {
					LogPortal.error("[{}]代付定时任务，代付提交失败,商户号:[{}],订单号[{}],调用通道[id:{},name:{}]", traceId,
							payOrderDTO.getMerchantId(), payOrderDTO.getMerchantOrderNo(), substitutePayConfigDTO.getId(),
							substitutePayConfigDTO.getChannelName());
					return false;
				}
				String channelOrderNo = channelResResult.getString("channelOrderNo");
				Integer status = channelResResult.getInteger("status");
				String failReason = channelResResult.getString("failReason");
				status = status == null ? Integer.valueOf(1) : status;


				merchantPayOrder.setChannelOrderNo(channelOrderNo);
				merchantPayOrder.setStatus(status);
				merchantPayOrder.setFailReason(failReason);

				if (MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus().equals(status)) {
					merchantPayOrder.setQueryFlag(1);
				}
				else if (MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(status)) {
					MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
					merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
					merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + payOrderDTO.getAmount() + "]");
					merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
					merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount().negate());
					changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "BB");
				}
				else if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(status)) {
					MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
					merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
					merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + payOrderDTO.getAmount() + "]");
					merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount().negate());
					changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "BB");
				}
			} catch (Exception e) {
				LogPortal.error("[{}]商户号:[{}]发起代付,订单号[{}],调用通道[id:{},name:{}]发生{}异常", e, traceId,
						payOrderDTO.getMerchantId(), payOrderDTO.getMerchantOrderNo(), substitutePayConfigDTO.getId(),
						substitutePayConfigDTO.getChannelName(), e.getClass().getName());
				return false;
			}
		}
		else {
			merchantPayOrder.setChannelId(-1);
			merchantPayOrder.setChannelCode("ERROR");
			merchantPayOrder.setChannelName("没有可用代付通道");
			merchantPayOrder.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrder.setFailReason(failMsg);

			//可提现余额返回
			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			merchantAccountOptions.setMerchantId(payOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + payOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + payOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(payOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, payOrderDTO.getMerchantOrderNo(), "BB");
		}
		merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);
		return true;
	}

	private boolean createBathUserTransferPayOrder(MerchantPayOrderDTO payOrderDTO) {
		log.info("---创建单个代付订单payOrderDTO：{}", JSONObject.toJSONString(payOrderDTO));

		String traceId = SnowFlakeUtils.getTraceId();
		BigDecimal totalTradeAmt = payOrderDTO.getAmount();

		BigDecimal amount = totalTradeAmt.subtract(payOrderDTO.getFee());

		MerchantPayOrder merchantPayOrder = new MerchantPayOrder();
		merchantPayOrder.setId(payOrderDTO.getId());

		merchantPayOrder.setChannelId(1);
		merchantPayOrder.setChannelCode("ayb");
		merchantPayOrder.setChannelName("爱游宝");
		merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);

		//校验是否绑定了爱游宝
		aybUserTransferBind aybUserTransferBind = aybUserTransferBindService.getByMerchantId(payOrderDTO.getMerchantId());
		if (aybUserTransferBind == null) {
			merchantPayOrder.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrder.setFailReason("请先在三方支付配置中绑定爱游宝代付");
			merchantPayOrder.setQueryFlag(0);
			merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);
			return false;
		}

		// 调用通道发起代付
		AybUserTransferOrderCreateReq req = new AybUserTransferOrderCreateReq();
		req.setTraceId(SnowFlakeUtils.getTraceId());
		req.setMerchantId(payOrderDTO.getMerchantId());
		req.setMerchantOrderNo(payOrderDTO.getMerchantOrderNo());
		req.setPartitionName("--");
		req.setGameAccount("--");
		req.setToGameAccount("--");
		req.setToName(payOrderDTO.getAccountName());
		req.setToPhone(payOrderDTO.getAccountNo());
		req.setAppliedAmount(payOrderDTO.getAmount());
		req.setFeeAmt(BigDecimal.ZERO);
		req.setRemark(payOrderDTO.getRemark());
		req.setAppliedTime(DateUtils.getNowDate());


		JSONObject channelResResult;
		try {
			channelResResult = aybUserTransferHandler.createOrder(req);
			if (channelResResult == null) {
				LogPortal.error("[{}]代付定时任务，代付提交失败,商户号:[{}],订单号[{}],调用通道[id:{},name:{}]", traceId,
						payOrderDTO.getMerchantId(), payOrderDTO.getMerchantOrderNo(), 1, "爱游宝");
				return false;
			}
			String channelOrderNo = channelResResult.getString("channelOrderNo");
			Integer status = channelResResult.getInteger("status");
			String failReason = channelResResult.getString("failReason");
			status = status == null ? Integer.valueOf(1) : status;


			merchantPayOrder.setChannelOrderNo(channelOrderNo);
			merchantPayOrder.setStatus(status);
			merchantPayOrder.setFailReason(failReason);

			if (MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus().equals(status)) {
				merchantPayOrder.setQueryFlag(1);
			}
		} catch (Exception e) {
			LogPortal.error("[{}]商户号:[{}]【创建单个代付订单】,订单号[{}],调用通道[id:{},name:{}]发生{}异常", e, traceId,
					payOrderDTO.getMerchantId(), payOrderDTO.getMerchantOrderNo(), 1, "爱游宝", e.getClass().getName());
			return false;
		}

		merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrder);
		return true;
	}

	@Override
	public boolean QiYiPayNotify(String traceId, String status, String orderNo, String channelOrderNo) {
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 奇异平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		if (!"3".equals(status) && !"2".equals(status) && !"1".equals(status)) {
			LogPortal.info("{} 奇异平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 奇异平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 奇异平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("1".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else if ("2".equals(status) || "3".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			if ("2".equals(status)) {
				merchantPayOrderDTO.setFailReason("接口方:管理员驳回");
			}
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean WanWPayNotify(String traceId, Map<String, String> reqParmMap) {
		String orderNo = reqParmMap.get("orderid");
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 玩玩代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		String status = reqParmMap.get("code");
		if (StringUtils.isEmpty(status) || "100".equals(status)) {
			LogPortal.info("{} 提现玩玩代付异步通知 订单号[{}]渠道状态[{}]为空或为处理中，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 玩玩代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		Map<String, String> signMap = new LinkedHashMap<>();
		signMap.put("version", reqParmMap.get("version"));
		signMap.put("cid", reqParmMap.get("cid"));
		signMap.put("orderid", reqParmMap.get("orderid"));
		signMap.put("money", reqParmMap.get("money"));
		signMap.put("tradeid", reqParmMap.get("tradeid"));
		signMap.put("code", reqParmMap.get("code"));
		signMap.put("time", reqParmMap.get("time"));
		String ownSign = WanWSignUtil.getSign(traceId, "玩玩代付异步通知", signMap, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(reqParmMap.get("sign"))) {
			LogPortal.error("{} 提现玩玩代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderNo);
			return false;
		}
		String channelOrderNo = reqParmMap.get("tradeid");
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 玩玩代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("0".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			merchantPayOrderDTO.setFailReason(reqParmMap.get("err"));
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public MerchantPayOrderDTO getMerchantPayOrderByChannelOrderNo(String channelOrderNo) {
		return BeanConvertUtils.convert(merchantPayOrderMapper.getMerchantPayOrderByChannelOrderNo(channelOrderNo), MerchantPayOrderDTO.class);
	}

	@Override
	public boolean XingYouPayNotify(String traceId, String status, String orderNo) {
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 星游平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		if (!"3".equals(status) && !"2".equals(status)) {
			LogPortal.info("{} 星游平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 星游平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 星游平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("2".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else if ("3".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean YouKaPayNotify(String traceId, String status, String orderId, String channelSign, String amount) {
		if (StringUtils.isEmpty(orderId)) {
			LogPortal.info("{} 优卡平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		if (!"0".equals(status) && !"1".equals(status) && !"2".equals(status)) {
			LogPortal.info("{} 优卡平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderId, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderId);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 优卡平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderId);
			return true;
		}
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		String ownSign = YouKaSignUtil.getAgentPayNotifySign(traceId, orderId, status, amount, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(channelSign)) {
			LogPortal.error("{} 优卡平台代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderId);
			return false;
		}
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 优卡平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderId, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("0".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else if ("1".equals(status) || "2".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean HuanDongPayNotify(String traceId, String status, String orderNo, String channelOrderNo, Map<String, String> signMap, String channelSign) {
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 欢动平台代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		// status判断 SUCCESS说明代付成功,返回其他均为失败
		if (StringUtils.isEmpty(status)) {
			LogPortal.info("{} 欢动平台代付异步通知 订单号[{}]渠道状态[{}]，渠道状态不是成功或失败，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 欢动平台代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}

		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		String ownSign = HuanDongSignUtil.getPaySign(traceId, "欢动平台代付异步通知", signMap, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(channelSign)) {
			LogPortal.error("{} 欢动平台代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderNo);
			return false;
		}

		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 欢动平台代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("SUCCESS".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			merchantPayOrderDTO.setFailReason("接口方返回失败");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean qcjhPayNotify(String traceId, Map<String, String> reqParmMap) {
		String orderNo = reqParmMap.get("out_trade_no");
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 七彩聚合代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		String status = reqParmMap.get("status");
		if (StringUtils.isEmpty(status)) {
			LogPortal.info("{} 提现七彩聚合代付异步通知 订单号[{}]渠道状态[{}]为空或为处理中，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 七彩聚合代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		Map<String, String> signMap = new LinkedHashMap<>();
		signMap.put("custid", reqParmMap.get("custid"));
		signMap.put("out_trade_no", reqParmMap.get("out_trade_no"));
		signMap.put("time_end", reqParmMap.get("time_end"));
		String ownSign = QCJHSignUtil.getSign(traceId, "七彩聚合代付异步通知", signMap, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(reqParmMap.get("sign"))) {
			LogPortal.error("{} 提现七彩聚合代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderNo);
			return false;
		}
		String channelOrderNo = reqParmMap.get("transaction_id");
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 七彩聚合代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("0".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			merchantPayOrderDTO.setFailReason("渠道返回失败");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean huYuPayNotify(String traceId, Map<String, String> reqParmMap) {
		String orderNo = reqParmMap.get("batchnumber");
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 互娱代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		// 状态,1:出款成功,不为1时见错误说明
		String status = reqParmMap.get("status");
		if (StringUtils.isEmpty(status)) {
			LogPortal.info("{} 提现互娱代付异步通知 订单号[{}]渠道状态[{}]为空或为处理中，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 互娱代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		Map<String, String> signMap = new LinkedHashMap<>();
		signMap.put("version", reqParmMap.get("version"));
		signMap.put("partner", reqParmMap.get("partner"));
		signMap.put("batchnumber", reqParmMap.get("batchnumber"));
		signMap.put("status", reqParmMap.get("status"));
		signMap.put("paymoney", reqParmMap.get("paymoney"));
		signMap.put("sysnumber", reqParmMap.get("sysnumber"));
		String ownSign = HuYuSignUtil.getSign(traceId, "互娱代付异步通知", signMap, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(reqParmMap.get("sign"))) {
			LogPortal.error("{} 提现互娱代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderNo);
			return false;
		}
		String channelOrderNo = reqParmMap.get("sysnumber");
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 互娱代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("1".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			merchantPayOrderDTO.setFailReason(reqParmMap.get("message"));
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	/**
	 * 更新爱游宝代付结果
	 *
	 * @author lch
	 * @date 2021/12/10
	 */
	@Override
	public void refresh() {
		List<MerchantPayOrder> orderList = listByChannelAndStatusInRecent7Days("ayb", MerchantPayOrderStatusEnum.PAY_PROCESSING.getStatus());
		if (CollectionUtils.isEmpty(orderList)) {
			return;
		}

		for (MerchantPayOrder order : orderList) {
			try {
				refreshOne(order);
			} catch (Exception e) {
				log.error("更新爱游宝代付(订单id:{})结果异常：{}", order.getMerchantOrderNo(), e.getMessage(), e);
			}
		}
	}

	/**
	 * 更新单个爱游宝代付结果
	 *
	 * @author lch
	 * @date 2021/12/10
	 */
	@Override
	public void refreshOne(MerchantPayOrder merchantPayOrder) {
		CommonResult commonResult = new CommonResult();
		commonResult.setCode(200);
		commonResult.setMsg("代付受理成功");
		String traceId = SnowFlakeUtils.getTraceId();

		AybUserTransferOrderQueryReq req = new AybUserTransferOrderQueryReq();
		req.setTraceId(traceId);
		req.setMerchantId(merchantPayOrder.getMerchantId());
		req.setMerchantOrderNo(merchantPayOrder.getMerchantOrderNo());

		try {
			AybUserTransferOrderQueryRes res = aybUserTransferHandler.queryOrder(req);
			if (res == null) {
				log.error("【更新单个爱游宝代付结果】交失败，请联系技术支持，错误码:" + traceId);
				MerchantPayOrder merchantPayOrderNew = new MerchantPayOrder();
				merchantPayOrderNew.setId(merchantPayOrder.getId());
				merchantPayOrderNew.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
				merchantPayOrderNew.setFailReason("响应数据为空");
				merchantPayOrderNew.setQueryFlag(0);
				merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrderNew);

				if (merchantPayOrder.getOrderSource() == 2) {
					GamePlayerCashOrderDTO dto1 = new GamePlayerCashOrderDTO();
					dto1.setMerchantOrderNo(merchantPayOrder.getMerchantOrderNo());
					dto1.setStatus(AliOrderStatus.CREAT.getCode());
					dto1.setFailReason("响应数据为空");
					gamePlayerCashOrderService.updateStatusByMerChantOrderNo(dto1);
				}

				return;
			}

			if (!"200".equals(res.getCode())) {
				log.error("【更新单个爱游宝代付结果】状态不是成功，记为失败，错误码:" + traceId);
				MerchantPayOrder merchantPayOrderNew = new MerchantPayOrder();
				merchantPayOrderNew.setId(merchantPayOrder.getId());
				merchantPayOrderNew.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
				merchantPayOrderNew.setFailReason(res.getMsg());
				merchantPayOrderNew.setQueryFlag(0);
				merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrderNew);

				if (merchantPayOrder.getOrderSource() == 2) {
					GamePlayerCashOrderDTO dto1 = new GamePlayerCashOrderDTO();
					dto1.setMerchantOrderNo(merchantPayOrder.getMerchantOrderNo());
					dto1.setStatus(AliOrderStatus.CREAT.getCode());
					dto1.setFailReason(res.getMsg());
					gamePlayerCashOrderService.updateStatusByMerChantOrderNo(dto1);
				}

				return;
			}

			if (!"SUCCESS".equals(res.getStatus())) {
				log.error("【更新单个爱游宝代付结果】状态不是成功，不作处理，错误码:" + traceId);
				return;
			}

			MerchantPayOrder merchantPayOrderNew = new MerchantPayOrder();
			merchantPayOrderNew.setId(merchantPayOrder.getId());
			merchantPayOrderNew.setPayType("BALANCE".equals(res.getPaymentType()) ? 2 : 0);
			merchantPayOrderNew.setBankName(res.getBankName());
			merchantPayOrderNew.setFinishTime(res.getCompleteDateTime());
			merchantPayOrderNew.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderNew.setFailReason(MerchantPayOrderStatusEnum.PAY_SUCCESS.getDescription());
			merchantPayOrderNew.setQueryFlag(0);
			merchantPayOrderMapper.updateByPrimaryKeySelective(merchantPayOrderNew);

			if (merchantPayOrder.getOrderSource() == 2) {
				GamePlayerCashOrderDTO dto1 = new GamePlayerCashOrderDTO();
				dto1.setMerchantOrderNo(merchantPayOrder.getMerchantOrderNo());
				dto1.setStatus(AliOrderStatus.SUCCESS.getCode());
				dto1.setFailReason("付款成功");
				gamePlayerCashOrderService.updateStatusByMerChantOrderNo(dto1);
			}
		} catch (Exception e) {
			LogPortal.error("【更新单个爱游宝代付结果】{} 商户号:{} 发起代付，调用通道 发生{}异常", e, traceId, merchantPayOrder.getMerchantId(), e.getClass().getName());
		}
	}

	/**
	 * 根据状态获取数组
	 *
	 * @author lch
	 * @date 2021/12/10
	 */
	@Override
	public List<MerchantPayOrder> listByStatus(Integer status) {
		Example example = new Example(MerchantPayOrder.class);
		example.createCriteria().andEqualTo(MerchantPayOrder.Fields.status, status);
		List<MerchantPayOrder> orderList = merchantPayOrderMapper.selectByExample(example);
		return orderList != null ? orderList : Lists.newLinkedList();
	}

	/**
	 * 根据状态获取数组最近七天的数据
	 *
	 * @author lch
	 * @date 2021/12/10
	 */
	public List<MerchantPayOrder> listByChannelAndStatusInRecent7Days(String channelCode, Integer status) {
		Example example = new Example(MerchantPayOrder.class);
		Example.Criteria criteria = example.createCriteria();
		criteria.andEqualTo(MerchantPayOrder.Fields.status, status);
		criteria.andEqualTo(MerchantPayOrder.Fields.channelCode, channelCode);
		criteria.andEqualTo(MerchantPayOrder.Fields.queryFlag, YesNoFlagEnum.YES.getCode());
		criteria.andBetween(MerchantPayOrder.Fields.applyTime, DateUtils.getDayBeforeDay(6), DateUtils.getNowDate());
		List<MerchantPayOrder> orderList = merchantPayOrderMapper.selectByExample(example);
		return orderList != null ? orderList : Lists.newLinkedList();
	}

	@Override
	public boolean faKaPayNotify(String traceId, Map<String, String> reqParmMap) {
		String orderNo = reqParmMap.get("requestId");
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 发卡代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		String status = reqParmMap.get("status");
		if (StringUtils.isEmpty(status)) {
			LogPortal.info("{} 提现发卡代付异步通知 订单号[{}]渠道状态[{}]为空或为处理中，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 发卡代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		String ownSign = FaKaSignUtil.getSign(traceId, "发卡代付异步通知", reqParmMap, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(reqParmMap.get("code"))) {
			LogPortal.error("{} 提现发卡代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderNo);
			return false;
		}
		String channelOrderNo = reqParmMap.get("serialNumber");
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 发卡代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("SUCCESS".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			merchantPayOrderDTO.setFailReason("渠道返回失败");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}

	@Override
	public boolean sky98PayNotify(String traceId, Map<String, String> reqParmMap) {
		String orderNo = reqParmMap.get("requestId");
		if (StringUtils.isEmpty(orderNo)) {
			LogPortal.info("{} 捷付通代付异步通知的商户订单号数值为空，不进行后续操作", traceId);
			return true;
		}
		String status = reqParmMap.get("status");
		if (StringUtils.isEmpty(status)) {
			LogPortal.info("{} 提现捷付通代付异步通知 订单号[{}]渠道状态[{}]为空或为处理中，不进行后续操作", traceId, orderNo, status);
			return true;
		}
		MerchantPayOrderDTO merchantPayOrderDTO = getMerchantPayOrderByMerchantOrderNo(orderNo);
		if (merchantPayOrderDTO == null) {
			LogPortal.error("{} 捷付通代付异步通知 商户订单号[{}]在我方系统查询不到", traceId, orderNo);
			return true;
		}
		SubstitutePayConfigDTO substitutePayConfigDTO = substitutePayConfigService.getSubstitutePayConfigById(merchantPayOrderDTO.getChannelId());
		String ownSign = FaKaSignUtil.getSign(traceId, "捷付通代付异步通知", reqParmMap, substitutePayConfigDTO.getWanXiangPayConfigParamVO().getKey());
		if (!ownSign.equalsIgnoreCase(reqParmMap.get("code"))) {
			LogPortal.error("{} 提现捷付通代付异步通知 商户订单号[{}] 签名验证失败", traceId, orderNo);
			return false;
		}
		String channelOrderNo = reqParmMap.get("serialNumber");
		if (MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus().equals(merchantPayOrderDTO.getStatus())
				|| MerchantPayOrderStatusEnum.PAY_FAIL.getStatus().equals(merchantPayOrderDTO.getStatus())) {
			LogPortal.error("{} 捷付通代付异步通知 商户订单号[{}]状态已为终态，不用再更新订单状态，当前状态是[{}]，支付渠道推送过来的状态是[{}]", traceId, orderNo, merchantPayOrderDTO.getStatus(), status);
			return true;
		}
		Date currentDate = DateUtils.getNowDate();
		if ("SUCCESS".equals(status)) {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_SUCCESS.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付成功提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]账号余额减少[" + totalTradeAmt + "]");
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "C");
		}
		else {
			merchantPayOrderDTO.setStatus(MerchantPayOrderStatusEnum.PAY_FAIL.getStatus());
			merchantPayOrderDTO.setQueryFlag(0);
			merchantPayOrderDTO.setFinishTime(currentDate);

			MerchantAccountOptions merchantAccountOptions = new MerchantAccountOptions();
			BigDecimal totalTradeAmt = merchantPayOrderDTO.getAmount();
			merchantAccountOptions.setMerchantId(merchantPayOrderDTO.getMerchantId());
			merchantAccountOptions.setOptionType("代付订单号" + merchantPayOrderDTO.getMerchantOrderNo() + "代付失败可提现金额增加[" + totalTradeAmt + "]提现中的金额减少[" + merchantPayOrderDTO.getAmount() + "]");
			merchantAccountOptions.setCashWithdrawal(totalTradeAmt);
			merchantAccountOptions.setCashWithdrawalIng(merchantPayOrderDTO.getAmount().negate());
			changeMerchantAccountAmt(merchantAccountOptions, merchantPayOrderDTO.getMerchantOrderNo(), "B");
			merchantPayOrderDTO.setFailReason("渠道返回失败");
		}
		merchantPayOrderDTO.setLastUpdateTime(currentDate);
		merchantPayOrderDTO.setChannelOrderNo(channelOrderNo);
		merchantPayOrderMapper.updateByPrimaryKeySelective(BeanConvertUtils.convert(merchantPayOrderDTO, MerchantPayOrder.class));
		return true;
	}


}
